from django.core.paginator import Paginator
from django.conf import settings
from django.http import HttpResponseRedirect, FileResponse
from django.urls import reverse

from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.decorators import action
from rest_framework import serializers

import main.migrates.sql as table_sql

import jwt,requests
from main.report.models import ReportInterface, InterfaceFields, ReportInfo, ModuleInfo, PlatformInfo
from main.utils.util_response import SuccessResponse,DetailResponse
from main.utils.util_db import MySqlHandler
from main.utils.util_datetime import getNowTimestamp
from main.utils.serializer import set_choice_field_internal_value

handler = MySqlHandler(settings.DB_INSTANCE)


class InterfaceFieldsSerializer(serializers.ModelSerializer):
    update_datetime=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    create_datetime=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    class Meta:
        model = InterfaceFields
        fields ='__all__'

    # def create(self, validated_data):
    #     # validated_data['interface_id']=self.context.get('interface_id')
    #     return InterfaceFields.objects.create(**validated_data)

    # def update(self, instance, validated_data):
    #     return InterfaceFields.objects.filter(id=instance.id).update(**validated_data)
    
    def to_internal_value(self, data):
        fields = self.fields
        set_choice_field_internal_value(fields, 'interface_data_type', data)
        set_choice_field_internal_value(fields, 'interface_para_type', data)
        set_choice_field_internal_value(fields, 'interface_export_flag', data)
        set_choice_field_internal_value(fields, 'interface_show_flag', data)
        return super().to_internal_value(data)
    
    def to_representation(self, instance):
        instance.interface_data_type = InterfaceFields.get_interface_data_type_display(instance)
        instance.interface_para_type = InterfaceFields.get_interface_para_type_display(instance)
        instance.interface_export_flag = InterfaceFields.get_interface_export_flag_display(instance)
        instance.interface_show_flag = InterfaceFields.get_interface_show_flag_display(instance)
        return super().to_representation(instance)
    
    
class InterfaceSerializer(serializers.ModelSerializer):
    update_datetime=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    create_datetime=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    interface_fields = InterfaceFieldsSerializer(many=True)

    class Meta:
        model = ReportInterface
        fields ='__all__'

    #     return None
    def to_representation(self, instance):
        '''
        重写to_representation方法，将数据库中存储的is_paging等字段值转换为前端显示的值
        '''
        if self.context.get('query_fields', False):
            # 给ReeportInterface添加字段属性
            instance.interface_fields = InterfaceFields.objects.filter(interface_id=instance.id)
        else:
            instance.interface_fields = None
        instance.is_paging = ReportInterface.get_is_paging_display(instance)
        instance.is_second_table = ReportInterface.get_is_second_table_display(instance)
        instance.is_total = ReportInterface.get_is_total_display(instance)
        instance.is_date_option=ReportInterface.get_is_date_option_display(instance)
        instance.is_login_visit=ReportInterface.get_is_login_visit_display(instance)
        instance.alarm_type = ReportInterface.get_alarm_type_display(instance)
        return super().to_representation(instance)

    def to_internal_value(self, data):
        '''
        重写to_internal_value方法，将前端传过来的is_paging等字段值转换为数据库中存储的值
        '''
        fields = self.fields
        set_choice_field_internal_value(fields,'is_paging',data)
        set_choice_field_internal_value(fields,'is_total',data)
        set_choice_field_internal_value(fields,'is_date_option',data)
        set_choice_field_internal_value(fields,'is_second_table',data)
        set_choice_field_internal_value(fields,'is_login_visit',data)
        set_choice_field_internal_value(fields,'alarm_type',data)
        return super().to_internal_value(data)

    def create(self, validated_data):
        interface_fields = validated_data.pop('interface_fields')
        # print("create", interface_fields)
        instance = super().create(validated_data)
        for field_values in interface_fields:
            field_values['interface_id'] = instance.id
            InterfaceFields(**field_values).save()
        return instance
    
    def update(self, instance, validated_data):
        # interface_fields = validated_data.pop('interface_fields')
        interface_fields = self.initial_data.get('interface_fields')
        # print("update", interface_fields)
        # interface_fields = self.initial_data.get('interface_fields')
        instance = super().update(instance, validated_data)
        for field_values in interface_fields:
            fields_instance = InterfaceFields.objects.filter(id=field_values.get('id')).first()
            if fields_instance:
                # InterfaceFields.objects.update(**field_values)
                ser=InterfaceFieldsSerializer(instance=fields_instance, data=field_values)
            else:
                ser = InterfaceFieldsSerializer(data=field_values)
            if ser.is_valid():
                ser.save()
        return instance
    

    
class InterfaceView(ViewSet):
    @action(methods=['post'], detail=False, url_path='platformModuleReportList')
    def get_platform_module_report_list(self, request):
        report_name = request.data.get('report_name')
        module_name = request.data.get('module_name')
        platform_name = request.data.get('platform_name')
        items = [item for item in handler.query( table_sql.SQL_REPORT_PLATFORM_MODULE_REPORT)]
        items = [item for item in items if (report_name == '' or item['report_name'] == report_name) 
                 and (module_name == '' or item['module_name'] == module_name )
                 and (platform_name =='' or item['platform_name'] == platform_name)]
        
        return DetailResponse(data=items)

    @action(methods=['post'], detail=False, url_path='list')
    def get_interface_list(self, request):
        name = request.data.get('interface_name', '')
        code = request.data.get('interface_code','')
        platform = request.data.get('platform_name','')
        module = request.data.get('module_name','')
        report = request.data.get('report_name','')
        limit = request.data.get('limit')
        page = request.data.get('page')
        interface_list = ReportInterface.objects.filter(
            interface_name__contains=name ,
            interface_code__contains=code ,
            report_name__contains=report ,
            module_name__contains=module ,
            platform_name__contains=platform
        )
        ser = InterfaceSerializer(instance = interface_list, many = True, context={'query_fields':False})
        p = Paginator(ser.data, limit)
        page_data = p.get_page(page).object_list
        return SuccessResponse(data=page_data, total=p.count,page=page,limit=limit)

    @action(methods=['post'], detail=False, url_path='detail')
    def get_interface_info(self, request):
        interface_id = request.data.get('interface_id')
        interface_one = ReportInterface.objects.filter(id=interface_id).first()
        if interface_one:
          ser = InterfaceSerializer(instance=interface_one, context={'query_fields':True})
          return DetailResponse(data=ser.data)
        else:
          return DetailResponse(msg='接口不存在')

    @action(methods=['post'], detail=False, url_path='delete')
    def delete_interface_info(self, request):
        ReportInterface.objects.filter(id=request.data.get('interface_id')).delete()
        InterfaceFields.objects.filter(interface_id=request.data.get('interface_id')).delete()
        return DetailResponse(msg="delete success")
    
    @action(methods=['post'], detail=False, url_path='add')
    def add_interface_info(self, request):
        # 查询对象是否存在
        instance = ReportInterface.objects.filter(interface_code=request.data.get('interface_code')).first()
        if instance:
            # return DetailResponse(msg='接口已存在')
            ser = InterfaceSerializer(instance=instance, data=request.data)
        else:
            ser=InterfaceSerializer(data = request.data, context={'query_fields':True})
        if ser.is_valid():
            ser.save()
        else:
            return DetailResponse(msg=ser.errors)
        return DetailResponse(msg="add success", data=ser.data)
    
    @action(methods=['post'],detail=False, url_path='update')
    def update_interface_info(self, request):
        instance = ReportInterface.objects.filter(id=request.data.get('id')).first()
        ser = InterfaceSerializer(instance = instance, data=request.data, context={'query_fields':True})
        if ser.is_valid():
            ser.save()
        else:
            return DetailResponse(msg=ser.errors)
        return DetailResponse(msg="update success", data=ser.data)

    @action(methods=['post'], detail=False, url_path='fields')
    def get_interface_fields(self, request):
        interface_id = request.data.get('interface_id')
        interface_para_type = request.data.get('interface_para_type',[1,2])
        items = InterfaceFields.objects.filter(interface_id=interface_id, interface_para_type__in=interface_para_type)
        ser = InterfaceFieldsSerializer(instance=items, many=True)
        return DetailResponse(data=ser.data)
    
    
    @action(methods=['post'], detail=False, url_path='queryData')
    def get_report_data(self, request):
        env_type = request.data.get("env_type")
        if env_type == 1:
            url_prefix = settings.REPORT_INTERFACE_URL_PROD 
        else:
            url_prefix = settings.REPORT_INTERFACE_URL_DEV
            
        if not url_prefix:
            return DetailResponse(msg="未配置接口地址")
        full_url = url_prefix + '?interface_code='+request.data.get('interface_code')
        payload = request.data.get('payload')
        token = request.data.get('token')
        if not token:
            sub = '{ "clientType": 13, "dataStorageModel": 2, "storeId": 15, "tenantId": 197, "userId": 53 }'
            iss = 'qyapitest.qiyucloud.com.cn'
            iat = getNowTimestamp() - 60*60*1
            nbf = getNowTimestamp()- 60*60*1
            exp = getNowTimestamp() + 60*60*5 
            data = {
            "sub":sub,
            "iss":iss,
            "iat":iat,
            "nbf":nbf,
            "exp":exp
            }
            token = jwt.encode(data, settings.JWT_KEY, algorithm='HS256')
        header ={
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '+ token
        }
        # print("token",token)
        resp=requests.post(url=full_url, headers=header, json=payload)
        if resp.status_code == 200:
            return DetailResponse(msg="获取成功", data=resp.json())
        else:
            return DetailResponse(msg="获取失败" + str(resp.content))
    


